package com.meiqiongproperty.yiguanjia.utils.image;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.os.Build;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Chen
 * @version V1.0
 * @package com.sameway.cnotes.utils.image
 * @date 17/2/6
 */
public class ImageHelper {

    private static final int DEFAULT_SCAL_QIALITY = 90;

    private static final int DEFAULT_SCAL_SIZE = 1000;



    /**
     * 图片去色,返回灰度图片
     *
     * @param bmpOriginal
     *            传入的图片
     * @return 去色后的图片
     */
    public static Bitmap toGrayscale(Bitmap bmpOriginal) {
        int width, height;
        height = bmpOriginal.getHeight();
        width = bmpOriginal.getWidth();

        Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas c = new Canvas(bmpGrayscale);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmpOriginal, 0, 0, paint);
        return bmpGrayscale;
    }

    /**
     * 缩放并旋转图片文件
     *
     * @param oldPathFile
     * @param newPathFile
     * @throws Exception
     */
    public static void scalAndRotaing(String oldPathFile, String newPathFile) throws Exception {
        Bitmap scalBitmap = scal(oldPathFile);
        Bitmap rotaingBitMap = rotaingImageViewByPath(oldPathFile, scalBitmap);
        bitmap2File(rotaingBitMap, newPathFile, DEFAULT_SCAL_QIALITY);

        if (scalBitmap != null && !scalBitmap.isRecycled()) {
            scalBitmap.recycle();
            scalBitmap = null;
//			System.gc();
        }
    }

    /**
     * 缩放并保存到新文件
     *
     * @param newPathFile
     * @param bitmap
     * @throws Exception
     */
    public static void scaleAndSaveImage(String newPathFile, Bitmap bitmap) throws Exception {
        Bitmap scalBitmap = scal(bitmap);
        bitmap2File(scalBitmap, newPathFile, DEFAULT_SCAL_QIALITY);
    }

    public static Bitmap scal(Bitmap bm) throws Exception {
        return scal(bm, DEFAULT_SCAL_SIZE, DEFAULT_SCAL_SIZE);
    }
    public static Bitmap scal(Bitmap bm, int w, int h) throws Exception {
        int width = bm.getWidth();
        int height = bm.getHeight();
        int max = Math.max(width, height);
        Matrix mtrix = new Matrix();
        if (max > w) {
            float scale = (float) w / Math.max(width, height);
            mtrix.reset();
            mtrix.postScale(scale, scale);
            Bitmap newBm = Bitmap.createBitmap(bm, 0, 0, width, height, mtrix, true);

//			if (bm != newBm && !bm.isRecycled()) {
//				bm.recycle();
//			}

            return newBm;
        }

        return bm;
    }

    public static Bitmap scal(String oldPathFile) throws Exception {
        Bitmap bm = ImageHelper.getSmallBitmap(oldPathFile);
        return scal(bm);
    }

    public static void saveImageFile(File f, Bitmap bm) throws Exception {
        bitmap2File(bm, f.getAbsolutePath(), 100);
    }

    public static void bitmap2File(Bitmap bitmap, String newFilePath, int quality) throws Exception {
        File destFile = new File(newFilePath);
        destFile.createNewFile();
        Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.JPEG;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(destFile);
            bitmap.compress(compressFormat, quality, fos);
            fos.flush();
        } finally {
            if (fos != null) {
                fos.close();
                fos = null;
            }

            if (!bitmap.isRecycled()) {
                bitmap.recycle();
                bitmap = null;
//				System.gc();
            }
        }
    }

    public static Bitmap rotaingImage(String filePath) {
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inSampleSize = 1;
        File file = new File(filePath);
        int degree = readPictureDegree(file.getAbsolutePath());
        Bitmap cameraBitmap = BitmapFactory.decodeFile(filePath, bitmapOptions);
        if (cameraBitmap == null) {
            return null;
        }
        Bitmap bitmap = cameraBitmap;
        return rotaingImageView(degree, bitmap);
    }

    public static boolean rotaingImage2FileNewPath(String filePath, String newFilePath) throws Exception {
        Bitmap bitmap = rotaingImage(filePath);
        if (bitmap == null) {
            return false;
        }
        bitmap2File(bitmap, newFilePath, 100);
        return true;
    }

    /**
     * 根据路径获得突破并压缩返回bitmap用于显示
     *
     * @param imagesrc
     * @return
     */
    public static Bitmap getSmallBitmap(String filePath) {
        return getSmallBitmap(filePath, DEFAULT_SCAL_SIZE, DEFAULT_SCAL_SIZE);
    }

    public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);
    }

    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
        }

        return inSampleSize;
    }

    public static Bitmap rotaingImageViewByPath(String path, Bitmap bitmap) {
        return rotaingImageView(readPictureDegree(path), bitmap);
    }

    /**
     * 旋转图片
     *
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {

        if (angle == 0) {
            return bitmap;
        }

        // 旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap newBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

//		if (bitmap != newBm && !bitmap.isRecycled()) {
//			bitmap.recycle();
//			return newBm;
//		}

        return newBm;
    }

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path
     *            图片绝对路径
     * @return degree旋转的角度
     */
    @TargetApi(Build.VERSION_CODES.ECLAIR)
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    public static void setImageViewWithResource(Context context, ImageView iv, int resId) {
        if (iv == null)
            return;

        Bitmap bp = getBitmapByResource(context, resId);
        if(bp != null){
            iv.setImageBitmap(bp);
        }
    }

    public static Bitmap getBitmapByResource(Context context, int resId){
        return getBitmapByResource(context, resId, DEFAULT_SCAL_SIZE, DEFAULT_SCAL_SIZE);
    }
    public static Bitmap getBitmapByResource(Context context, int resId, int width, int height){
        final BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        Bitmap bp = null;
        try {
            InputStream is = context.getResources().openRawResource(resId);
            bp = BitmapFactory.decodeStream(is, null, opt);
            bp = scal(bp, width, height);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bp;
    }

    /**
     * 转换图片成圆形
     *
     * @param bitmap
     *            传入Bitmap对象
     * @return
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            left = 0;
            top = 0;
            right = width;
            bottom = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);// 设置画笔无锯齿

        canvas.drawARGB(0, 0, 0, 0); // 填充整个Canvas
        paint.setColor(color);

        // 以下有两种方法画圆,drawRounRect和drawCircle
        // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);// 画圆角矩形，第一个参数为图形显示区域，第二个参数和第三个参数分别是水平圆角半径和垂直圆角半径。
        canvas.drawCircle(roundPx, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));// 设置两张图片相交时的模式,参考http://trylovecatch.iteye.com/blog/1189452
        canvas.drawBitmap(bitmap, src, dst, paint); //以Mode.SRC_IN模式合并bitmap和已经draw了的Circle

        return output;
    }
}
